//console.log(window.Modernizr);
   
$(document).ready(function(e) {
    
	
	var pageZoom=0,pageOffset=[],pageSize=[];
	var siteUrl='';
	
	var headerBox=$('header');
	var footerBox=$('footer');
	var wrapBox=$('.wrap');
	var mainBox=$('.main');
	var pageBox=$('.pages');
	var pageBg=pageBox.children('.background');
	var pageNow=0;
	var pageLast=-1;
	var pageMax=pageBox.length;
	//console.log('pageMax:'+pageMax);
	var pageWd,pageHt;
	var pageSp=1;
	var testBox=$('#testBox');
	var testHt=testBox.outerHeight();
	var linkBar=$('#link');
	var pageScroll=0;
	var pageList=[];
	var pageTimeline=[];
	
	var loadBox=$('#popLoad');

    var submenuBox=$('.submenu').children();
	var submenuTimer;
	
	var navBox=$('nav');
	var menuBox=navBox.find('li');	
	var navBtn=navBox.children('a.btn');
	var navMask=navBox.children('.mask');
	var navTimer;
	

	
	var workPop=$('#popWorks');//内容弹出窗
	var workClose=workPop.find('.close');////内容弹出窗关闭按钮
	var workBox=workPop.children(".box");//图片和视频容器  	


    var fuckAndroidReSize = false;
    var canvas, stage, exportRoot;
    var cav_zk;
    var P1;




    //各种需要定宽高
    pageWd=$(window).width();
	pageHt=$(window).height();//去掉header和footer的实际可见高度
    wrapBox.css({height: pageHt,width: pageWd});
	mainBox.css({height: pageHt,width: pageWd});
	pageBox.css({height: pageHt,width: pageWd});
    $('.form_ar').css({height: pageHt,width: pageWd});
    $('.share_ar').css({height: pageHt,width: pageWd});
    $('.winner_ar').css({height: pageHt,width: pageWd});
    $('.winner_ar_main').css({height: pageHt,width: pageWd});
    $('.rule_ar_main').css({height: pageHt,width: pageWd});




    $( window ).on("orientationchange", function( event ) { 
        
            if(event.orientation){ 
                if(event.orientation == 'portrait'){ 
                    $(".tvcVideoBox").css({top:'150px',height:'auto'});
                    $(".tVideo").css({top:'0px'});
                    $(".vClose").css({top:'-20px'});
                    //box.hide();
                } 
                else if(event.orientation == 'landscape') { //横屏
                    $(".tvcVideoBox").css({top:'0px',height:'80%'});
                    $(".tVideo").css({top:'-80px'});
                    $(".vClose").css({top:'20px'});
                    //box.show();
                    
                } 
            } 
        });


    //导航
    $('.menu').height(pageHt);
    $('.menu_icon').click(function(){
        if($('.menu').hasClass('active')){
            $('.menu').removeClass('active');
            $('.menu').addClass('activet');
        }else{
            $('.menu').removeClass('activet');
            $('.menu').addClass('active');
        };
    });
    $('.menu_close img').click(function(){
        if($('.menu').hasClass('active')){
            $('.menu').removeClass('active');
            $('.menu').addClass('activet');
        }
    });
    $('.menu ul li').click(function(){
        if($('.menu').hasClass('active')){
            $('.menu').removeClass('active');
            $('.menu').addClass('activet');
        }
    });
    $('.backtop').click(function(){
        pageNow = 0;
        scrollFunc();
        pageChange();
    });
    $('.govideo').click(function(){
        pageNow = 4;
        scrollFunc();
        pageChange();
    });

    $('.gomedia').click(function(){
        pageNow = 5;
        scrollFunc();
        pageChange();
    });



    //人物页面视频播放
    $('.popman_video_icon').click(function(){
        var dt = $(this).attr('dt');
        //$('.muice_ic').addClass('off');
        //$('.muice_ic').html('<img src="images/muice_icon_off.png">');
        //$('.aud')[0].pause();
        switch(dt){
            case '1':
                $('#videoBox').html('<video id="videose" src="http://k.youku.com/player/getFlvPath/sid/14291649192185156459f_01/st/mp4/fileid/030008010054B59226283708B7976D55C33ADC-18D6-D0C2-EBAD-F51F778A87D8?K=031d2d36bd7ef954261e49b7&hd=1&ts=60&ctype=51&token=7869&ev=1&oip=1917863302&ep=09qcMMArO7fKw%2F0TPP17eexmYAnSqvbJkdYp2NiMG76EXOmZukBEM8xGQoK%2FXJM7%2Fjn4rcg%2BoYERbMO5zjiHCoGHTC5ODNcBddXaDOY0NdX4E1KVB%2FjDJ%2B1QVBNB6iQL" controls="controls" autoplay="autoplay" style="width:100%;height:30%;margin-top:150px;"></video>')
                break;
            case '2':
                $('#videoBox').html('<video id="videose" src="http://k.youku.com/player/getFlvPath/sid/14291649192185156459f_01/st/mp4/fileid/030008010054B59226283708B7976D55C33ADC-18D6-D0C2-EBAD-F51F778A87D8?K=031d2d36bd7ef954261e49b7&hd=1&ts=60&ctype=51&token=7869&ev=1&oip=1917863302&ep=09qcMMArO7fKw%2F0TPP17eexmYAnSqvbJkdYp2NiMG76EXOmZukBEM8xGQoK%2FXJM7%2Fjn4rcg%2BoYERbMO5zjiHCoGHTC5ODNcBddXaDOY0NdX4E1KVB%2FjDJ%2B1QVBNB6iQL" controls="controls" autoplay="autoplay" style="width:100%;height:30%;margin-top:150px;"></video>')
                break;
            case '3':
                $('#videoBox').html('<video id="videose" src="http://k.youku.com/player/getFlvPath/sid/14291649192185156459f_01/st/mp4/fileid/030008010054B59226283708B7976D55C33ADC-18D6-D0C2-EBAD-F51F778A87D8?K=031d2d36bd7ef954261e49b7&hd=1&ts=60&ctype=51&token=7869&ev=1&oip=1917863302&ep=09qcMMArO7fKw%2F0TPP17eexmYAnSqvbJkdYp2NiMG76EXOmZukBEM8xGQoK%2FXJM7%2Fjn4rcg%2BoYERbMO5zjiHCoGHTC5ODNcBddXaDOY0NdX4E1KVB%2FjDJ%2B1QVBNB6iQL" controls="controls" autoplay="autoplay" style="width:100%;height:30%;margin-top:150px;"></video>')
                break;
        }
        //$('#videoBox').html('<video id="videose" src="video/' + videonm + '.mp4" controls="controls" autoplay="autoplay" style="width:100%;height:30%;margin-top:150px;"></video>')
        $('#popVideo').show();
        $('.close').click(function(){
            $('#popVideo').hide();
            $('#videoBox').html('');
        });
    });

    //tvc视频播放
    $('.video_main_area').on('click','.tvc_video_img',function(){
        var fzk = $(this).attr('fzk');
        //$('.muice_ic').addClass('off');
        //$('.muice_ic').html('<img src="images/muice_icon_off.png">');
        //$('.aud')[0].pause();
        switch(fzk){
            case '1':
                console.log('1');
                $('#videoBox').html('<iframe height=352 width=640 style="margin-top:200px;" src="http://player.youku.com/embed/XOTM0MTQwMDY0" frameborder=0 allowfullscreen></iframe>')
                break;
            case '2':
                console.log('2');
                $('#videoBox').html('<iframe height=352 width=640 style="margin-top:200px;" src="http://player.youku.com/embed/XOTM0MTM2Mzky" frameborder=0 allowfullscreen></iframe>')
                break;
            case '3':
                console.log('3');
                $('#videoBox').html('<iframe height=352 width=640 style="margin-top:200px;" src="http://player.youku.com/embed/XOTM0MTM4NDIw" frameborder=0 allowfullscreen></iframe>')
                break;
            case '4':
                console.log('4');
                $('#videoBox').html('')
                break;
        }
        //$('#videoBox').html('<video id="videose" src="video/' + videonm + '.mp4" controls="controls" autoplay="autoplay" style="width:100%;height:30%;margin-top:150px;"></video>')
        $('#popVideo').show();
        $('.close').click(function(){
            $('#popVideo').hide();
            $('#videoBox').html('');
        });
    });


    //视频页面
    var gt = 1;
    function gt_video(){
        gt = $('.setvideo_img .active').attr('gt');
        var ge = gt - 1;
        $('.setvide_img_left').eq(ge).html('<img src="images/setvideo_img' + gt + '_on.png">')
        switch(gt)
        {
            case '1':
                $('.video_main_area').html('<img src="images/tvc1" class="tvc_video_img" fzk="1" />');
                break;
            case '2':
                $('.video_main_area').html('<img src="images/tvc2" class="tvc_video_img" fzk="2" />');
                break;
            case '3':
                $('.video_main_area').html('<img src="images/tvc3" class="tvc_video_img" fzk="3" />');
                break;
            case '4':
                //$('.video_main_area').html('<video id="videose2" src="http://ayer/getFlvPath/sid/342855150917051cee2d4_01/st/mp4/fileid/030008010054FD9F059B910644D3A05CF38B64-19B8-27ED-7FBF-58E970CEC2A5?K=ba016a82b8fc7c6c261e4663&hd=1&ts=60&ctype=51&token=9019&ev=1&oip=1917863302&ep=abvLqUu%2FwpBg0bYj%2BIEz%2FKxX43af8WH1kdYp2NiMG76pYDvkpsmQNLHiw%2BH4rL%2FXXwfPAGcWzwxjIpFV4WBDHDB3difEm9OTpCmf230Vre5%2BAJpYgrHEgXE5dcFO8RUd" controls="controls" style="width:100%;height:35%;"></video>');
                alert('敬请期待!')
                break;
        }
    };
    $('.setvide_img_left').click(function(){
        var ch = $('.setvideo_img .active').attr('gt');
        var dh = ch - 1;
        $('.setvide_img_left').eq(dh).html('<img src="images/setvideo_img' + ch + '_off.png">')
        $('.setvide_img_left').removeClass('active');
        $(this).addClass('active');
        gt_video();
    });






    //填表单隐藏头尾
    $('input').blur(function(){
        $('.header_t').show();
    });
    $('input').focus(function(){
        $('.header_t').hide();
    });



    //中奖名单打开－未上线
    $('.gowinner').click(function(){
        $('.winner_ar').show();
    });

    //中奖名单打开 关闭滚屏效果－上线
    $('.gowinner_m').click(function(){
        $('.winner_ar_main').show();
        swipe_off();
    });
    //中奖名单关闭 打开滚屏效果
    $('.winner_close').click(function(){
        $('.winner_ar_main').hide();
        swipe_on();
    });
    //活动规则打开 关闭滚屏效果
    $('.gorule').click(function(){
        $('.rule_ar_main').show();
        swipe_off();
    });
    //活动规则关闭 打开滚屏效果
    $('.rule_close').click(function(){
        $('.rule_ar_main').hide();
        swipe_on();
    });
    //提醒分享 点击关闭
    $('.share_ar').click(function(){
        $('.share_ar').hide();
    });
    //中奖名单未上线 点击关闭
    $('.winner_ar').click(function(){
        $('.winner_ar').hide();
    });
    //获得点赞数
    function getzanall(){
        $.ajax({
            type: "GET",
            url: "http://www.fabiachina.com/api/index.php/zan?time=" + new Date(),
            dataType: "json",
            success: function(data){
                $('.gg1').html(data.result[0].count);
                $('.gg2').html(data.result[1].count);
                $('.gg3').html(data.result[2].count);
                $('.gg4').html(data.result[3].count);
            }
        });
    }
    getzanall();
    //点赞
    var zanid;
    $('.popman_zan').click(function(){
        var zan_who = $(this).attr('zan');
        zanid = zan_who;
        $.ajax({
            type: "POST",
            url: "http://www.fabiachina.com/api/index.php/zan/" + zan_who,
            dataType: "json",
            success: function(data){ //点赞 表单出现 滚屏关闭
                $('.form_ar').show();
                getzanall();
                swipe_off();
            }
        });
    });
    //表单关闭
    $('.form_close').click(function(){
        $('.form_ar').hide();
        swipe_on();
    });
    //表单默认选中 是
    $(".yes").addClass("active");

    //表单redio选项
    $('.ted_ok').click(function(){
        $('.ted_ok').removeClass('active');
        $(this).addClass('active');
    });


    //提交表单
    $('.sub_maji').click(function(){
        var name = $('.ename').val();
        var mobile = $('.emobile').val();
        var flag = $('.ted_ok.active').attr('yne');
        var reg = /^1\d{10}$/;
        if ($.trim(name).length == 0) {
            alert('请填写姓名');
            return false;
        }
        if (!reg.test(mobile)) {
            alert('请正确填写手机号码');
            return false;
        }
        $.ajax({
            type: "POST",
            url: "http://www.fabiachina.com/api/index.php/user",
            data:'uname=' + name + '&mobile='+ mobile + '&flag=' + flag + '&zanid=' + zanid,
            dataType: "json",
            success: function(data){
                if(data.code==200){ //成功 恢复滚屏 表单层消失 分享提示层出现
                    swipe_on();
                    $('.form_ar').hide();
                    $('.share_ar').show();

                    var s=s_gi(s_account);
                    s.pageName="分享提示页M端";
                    s.channel="分享提示页M端";
                    s.t();
                }
            }
        });
    });

	init();
	
	function init() {


        androidBool = is_android();
        iphoneBool = is_iPhone();
        if (androidBool) {
            //alert(navigator.userAgent)
            var arr = navigator.userAgent.split(';')
            for (var i = 0; i < arr.length; i++) {
                var temp = arr[i].toLowerCase();
                if (temp.indexOf('android') != -1) {
                    androidVersion = temp.split('android')[1];
                    var num = androidVersion.split('.')[0] + '.' + androidVersion.split('.')[1];
                    androidVersion = Number(num);
                    // alert(arr[i].toLowerCase()+'/'+androidVersion)
                }


            }
            ;

        }


        creatList();
        creatBg();


        //获得页面page参数
        pageNow = 0;
        console.log('pageNow:' + pageNow);

        window_resize();
        $(window).on('resize', window_resize);


        //canvas

        P1 = function (canvas) {
            this.canvas = canvas;
            this.images = images || {};
            this.exportRoot = null;
            this.stage = null;
        }
        P1.prototype = {
            init: function () {
                createjs.MotionGuidePlugin.install();
                var manifest = [
                    {src: "images/lib_m_img_000001.jpg", id: "lib_m_img_000001"},
                    {src: "images/lib_m_img_000003.png", id: "lib_m_img_000003"},
                    {src: "images/lib_m_img_000004.png", id: "lib_m_img_000004"},
                    {src: "images/lib_m_img_000005.png", id: "lib_m_img_000005"},
                    {src: "images/lib_m_img_000007.png", id: "lib_m_img_000007"},
                    {src: "images/lib_m_img_000008.png", id: "lib_m_img_000008"},
                    {src: "images/lib_m_img_000009.png", id: "lib_m_img_000009"},
                    {src: "images/lib_m_img_000010.png", id: "lib_m_img_000010"},
                    {src: "images/lib_m_img_000018.png", id: "lib_m_img_000018"},
                    {src: "images/lib_m_img_000021.png", id: "lib_m_img_000021"}
                ];

                var loader = new createjs.LoadQueue(false);
                loader._self = this;
                loader.addEventListener("fileload", this.handleFileLoad);
                loader.addEventListener("complete", this.handleComplete);
                loader.loadManifest(manifest);

            },

            handleFileLoad: function (evt) {
                if (evt.item.type == "image") {
                    this.images[evt.item.id] = evt.result;
                }
            },

            handleComplete: function (e) {
                var loader = e.target;
                var _self = loader._self;

                _self.exportRoot = new lib.canvas0();

                _self.stage = new createjs.Stage(_self.canvas);
                _self.stage.addChild(_self.exportRoot);
                _self.stage.update();

                createjs.Ticker.setFPS(30);
                createjs.Ticker.addEventListener("tick", _self.stage);
            },
            onStop: function () {
                this.exportRoot.onStop();
                createjs.Ticker.removeEventListener("tick", this.stage);
            },

            rePlay: function () {
                createjs.Ticker.addEventListener("tick", this.stage);
                this.exportRoot.rePlay();
            }
        }


        addEvent();

    };


// 判断是否手机段
function is_android(){
	if(navigator.userAgent.match(/Android/i)) return true;
	else return false;
}
//是否iPhone手机
function is_iPhone(){
	if ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1))return true;
	else return false;
}



	function creatList(){
		var _now=-1;
		var boxes=mainBox.children();
		boxes.each(function(i, n) {
            if($(n).hasClass('pages')){
				pageList.push([_now+1,1]);
				_now++;
			}//end if
			else{
				var len=$(n).children('.pages').length;
				pageList.push([_now+1,len]);
				_now+=len;
			}//end else
        });
	}//end func





	
	//自适应
	function window_resize(){
		

		pageScroll=-pageHt*pageNow;		



        if(!fuckAndroidReSize){
            wrapBox.css({height: $(window).height(),width: $(window).width()});
	        mainBox.css({height: $(window).height(),width: $(window).width()});
		    pageBox.css({height: $(window).height(),width: $(window).width()});
        } 
        



        var box = $('#turnBox');


	}//end func
	

	
	
	function addEvent(){		
		
		//栏目切换
		//$(document).on('touchmove',noEvent);
		$('.wrap').on('swipeup',document_swipeup);
		$('.wrap').on('swipedown',document_swipedown);
		
		
	}//end func


	function creatBg(){
		pageBg.each(function(i, n) {
			var src=$(n).data('background');
			var img=$('<img>').attr({src:src}).appendTo($(n));
        });
	}//end func




	/*function window_orientationchange(e){
		var box=$('#turnBox');
		if(e.orientation=='landscape'){
			box.show();
			if(os.android) setTimeout(function(){
				box.css({width:$(window).width(),height:$(window).height()});
			},100);
		}//end if
		else box.hide();


	}//end func*/
    //滚屏关闭
	function swipe_off(e){

        $('.wrap').off('swipeup',document_swipeup);
        $('.wrap').off('swipedown',document_swipedown);
	}//end func	
    //滚屏打开
	function swipe_on(e){
        $('.wrap').on('swipeup',document_swipeup);
        $('.wrap').on('swipedown',document_swipedown);
	}//end func

	
	

	
	function document_swipeup(e){
		//console.log('swipe up');
		if(!mainBox.hasClass('moving') && pageNow!=pageMax-1){
			pageNow++;
			pageNow=pageNow>pageMax-1?pageMax-1:pageNow;
			pageChange();
		}//end func
	}//end func
	
	function document_swipedown(e){
		//console.log('swipe down');
		if(!mainBox.hasClass('moving') && pageNow!=0){
			pageNow--;
			pageNow=pageNow<0?0:pageNow;
			pageChange();
		}//end func
	}//end func


    //canvas
    cav_zk = new P1($("#canvas")[0]);
    cav_zk.init();

    //首页监测代码
    var s=s_gi(s_account);
    s.pageName="快乐真人售首页M端";
    s.channel="快乐真人售首页M端";
    s.t();


	function pageChange(){
        console.log(pageNow);
        $('.share_ar').hide();
        $('.winner_ar').hide();
        if($('.menu').hasClass('active')){
            $('.menu').removeClass('active');
            $('.menu').addClass('activet');
        }
        if(pageNow == '0'){
            cav_zk.rePlay();
        }
        else if(pageNow == '1'){
            $('.page1').addClass('active');
            var s=s_gi(s_account);
            s.pageName="角色脱口秀一哥页M端";
            s.channel="角色脱口秀一哥页M端";
            s.t();
        }
        else if(pageNow == '2'){
            $('.page2').addClass('active');
            var s=s_gi(s_account);
            s.pageName="角色说唱达人页M端";
            s.channel="角色说唱达人页M端";
            s.t();
        }
        else if(pageNow == '3'){
            $('.page3').addClass('active');
            var s=s_gi(s_account);
            s.pageName="角色舌尖食神页M端";
            s.channel="角色舌尖食神页M端";
            s.t();
        }
        else if(pageNow == '4'){
            $('.page4').addClass('active');
            var s=s_gi(s_account);
            s.pageName="视频鉴赏页M端";
            s.channel="视频鉴赏页M端";
            s.t();
        }
        else if(pageNow == '5'){
            $('.page5').addClass('active');
            var s=s_gi(s_account);
            s.pageName="媒体合作页M端";
            s.channel="媒体合作页M端";
            s.t();
        }
		//console.log('pageNow:'+pageNow);
		//console.log('pageLast:'+pageLast);
		if(pageLast>-1) var _last=pageToMenu(pageLast);
		var _now=pageToMenu(pageNow);
		menuBox.eq(_now).addClass('active').siblings().removeClass('active');
		if(pageList[_now][1]<1 && pageLast){
			var submenu=menuBox.eq(_last).children('.submenu');
			if(submenu.length>0) submenu.hide().children().removeClass('active');
		}//end if
		else if(pageList[_now][1]>1){
			var submenu=menuBox.eq(_now).children('.submenu').children();
			var id=pageNow-pageList[_now][0];
			submenu.eq(id).addClass('active').siblings().removeClass('active');
		}//end if
		scrollFunc();
		pageLast=pageNow;
   	}//end func	

	
	function pageToMenu(_now){
		var id;
		for(var i=0; i<pageList.length; i++){
			if(_now>=pageList[i][0] && _now<pageList[i][0]+pageList[i][1]){
				id=i;
				break;
			}//end if
		}//end for
		//console.log('menu_id:'+id);
		return id;
	}//end func
	
	function scrollFunc(){

		pageScroll=-pageHt*pageNow;
		mainBox.addClass('moving');
		//menuBoxOff();
		//TweenLite.to(mainBox, pageSp, {transform:'translate3d('+ 0 +'px,'+ pageScroll +'px,0px)', ease:Quart.easeInOut, onComplete:scrollComplete});
		TweenLite.to(mainBox, pageSp, {marginTop:pageScroll, ease:Quart.easeInOut, onComplete:scrollComplete});
	}//end func
	
	function scrollComplete(){

		if(pageNow>0){
			linkBar.hide();
			$('#testbar').show();
		}//end if
		else{
			linkBar.show();
			$('#testbar').hide();
		}//end else
		mainBox.removeClass('moving');
        if(pageNow >= 0){
            var oac = pageNow - 1;
            var pac = pageNow + 1;
            $('.pages').eq(oac).removeClass('active');
            $('.pages').eq(pac).removeClass('active');
        }
        //$('.pages').removeClass('active');
		//menuBoxOn();
	}//end func
	


	
});


//--------------------------------公共函数
	
	function noEvent(e){
		e.preventDefault();
	}//end func
	
	function randomPlus() {
			return Math.random()<0.5?-1:1;
	}//end func  随机正负
		
	function randomRange(min, max) {
			var randomNumber;
			randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
			return randomNumber;
	}//end func
	
	function getQueryString(name) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
		var r = window.location.search.substr(1).match(reg);
		if (r != null) return unescape(r[2]); return null;
	}//end func
	
	//打印json数据
	function jsonPrint(data){
		console.log("-----------------------------------------------------------------------------");
		for(var i=0; i<data.length; i++) objectPrint(data[i]);
		console.log("-----------------------------------------------------------------------------");
	}//end func
	
	//打印object数据
	function objectPrint(data){
		console.log("-----------------------------------------------------------------------------");
		var info="";
		for(var i in data) info+=i+":"+data[i]+"  "
		console.log(info);
		console.log("-----------------------------------------------------------------------------");
	}//end func
	
	function mathAutoSize(aryNum,aryMax){
				var aryNow=new Array()
				var aryRate= aryNum[0]/aryNum[1];
				aryNow[0] = aryMax[0];
				aryNow[1] = Math.round(aryNow[0]/aryRate);
				if(aryNow[1]<aryMax[1]){
					aryNow[1]=aryMax[1];
					aryNow[0] = Math.round(aryNow[1]*aryRate);
				}//end if				
				return aryNow;
	}//end func	



